<template>
	<view class="storeBox bluetooth">
		<u-popup v-model="visiable" mode="right" length="85%">
			<view class="top">
				<image @click="goToBack" src="https://www.yongshantuan.cn/images/yongshan/platformSide/downArrow.png"
					mode=""></image>
				<view class="">连接打印机</view>
			</view>

			<button @click="clickSearch" class='b-btn'>搜索蓝牙设备</button>
			<button @click="closeBLEConnection" class='b-btn btn-la'>断开连接</button>
			<!-- <text>蓝牙已经连接的设备：{{connectedDevice.deviceId}}</text> -->

			<view v-for="item in deviceList" :key='item.deviceId' @click="bindViewTap" :data-title="item.deviceId"
				:data-name="item.name" :data-advertisData="item.advertisServiceUUIDs" class='device-item'>
				<view v-if='item.RSSI != 0' :class="{connected: connectedDevice.deviceId == item.deviceId}">
					<view style="font-size: 16px">{{item.name}}</view>
					<view style="font-size: 14px">{{item.deviceId}}</view>
					<view style="font-size: 10px">信号强度: {{item.RSSI}}dBm ({{Math.max(0, item.RSSI + 100)}}%)</view>
					<view class='c-status'>{{ connectedDevice.deviceId == item.deviceId ? '已连接' : '未连接' }}</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		props: ['hideBluetoothBox', 'show', 'connectStatus'],
		data() {
			return {
				visiable: false,
				app: {},
				deviceList: [], // 搜索到的蓝牙设备
				services: [], // 一个蓝牙设备的服务
				listNum: 0,
				connectedDevice: {}, // 当前连接中的蓝牙设备，也用来判断是否已连接
				writeCharacter: false,
				readCharacter: false,
				notifyCharacter: false,
				isScanning: false,
				autoConnectDeviceId: '', 	// 是否自动获取到了设备id，即可用来判断是否执行自动连接
			}
		},
		onLoad() {
			console.log('bluetooth onload--- 这是页面的钩子函数，组件不执行')
		},
		created() {
			this.app = getApp();
			var _this = this;
			var that = this;
			
			this.app.globalData.setConnectedDevice = () => {
				_this.setUnconnectStatus();
			}
			this.app.globalData.queryPrinterStatus = (opt) => {
				_this.queryPrinterStatus(opt);
			}
			
			this.autoConnectDeviceId = uni.getStorageSync('printerDeviceId') || '';
			// 若已连接成功，BLEInformation的writeCharaterId、writeServiceId、notifyCharaterId、notifyServiceId不为空，print.vue中执行打印会使用到
			var writeCharaterId = this.app.globalData.BLEInformation.writeCharaterId;
			if (writeCharaterId) {
				_this.queryPrinterStatus()
				
			} else {
				if (this.autoConnectDeviceId) {
					console.log('执行蓝牙自动连接---')
					this.startSearch();
				}
			}
			
			return;  // 测试可放开
			
			this.deviceList = [
				{
					deviceId: '123',
					name: 'OSDJFLE',
					RSSI: 80,
				},{
					deviceId: '456',
					name: 'OSDJFLE',
					RSSI: 80,
				},{
					deviceId: '1278973',
					name: 'OSDJFLE',
					RSSI: 80,
				}
			]
			this.connectedDevice = {deviceId: '123'}
		},
		mounted() {
			var _this = this;
			wx.onBLEConnectionStateChange(res => {
				// 该方法回调中可以用于处理连接意外断开等异常情况
				console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
				if (!res.connected) {
					wx.showModal({
						title: '蓝牙已断开连接',
						showCancel: false
					})
					_this.setUnconnectStatus();
				}
			}) 
		},
		watch: {
			show(newVal) {
				console.log('watch show:', newVal)
				this.visiable = newVal;
			},
			visiable(newVal) {
				if (!newVal) {
					this.$emit('hideBluetoothBox');
					// this.clearData()
				} else {
					if (this.connectedDevice && Object.keys(this.connectedDevice).length) {
						// 已连接
					} else {
						// 每次打开，若没连接，则自动连接
						this.autoConnectDeviceId = uni.getStorageSync('printerDeviceId') || '';
						let obj = this.deviceList.find(val => val.deviceId == this.autoConnectDeviceId)
						if (obj) {
							this.connectBluetooth(this.autoConnectDeviceId);
						} else {
							this.startSearch();
						}
					}
					
				}
			},
			connectedDevice(val) {
				console.log('connectedDevice改变：', val);
				if (val && val.deviceId) {
					this.$emit('connectStatus', true)
				} else {
					this.$emit('connectStatus', false)
				}
			}
		},

		methods: {
			// 返回
			goToBack() {
				this.$emit('hideBluetoothBox');
			},

			// 断开与蓝牙设备的连接
			closeBLEConnection: function() {
				var _this = this;
				uni.showModal({
				  title: '确定断开连接',
				  success (res) {
				    if (res.confirm) {
					  uni.closeBLEConnection({
					  	deviceId: _this.app.globalData.BLEInformation.deviceId,
					  	success: function(){
					  		// _this.setUnconnectStatus(true);
					  	},
					  	complete: function(e) {
					  		console.warn(e);
							_this.setUnconnectStatus(true);
					  	}
					  })
				    } 
				  }
				})
			},
			
			// 设置断开状态
			setUnconnectStatus(showTip) {
				var _this = this;
				_this.app.globalData.BLEInformation.deviceId = '';
				_this.connectedDevice = {};
				if (showTip) {
					uni.showToast({
						title: '已断开连接',
						icon: 'none'
					})
				}
			},
			
			// 查询打印机状态
			queryPrinterStatus: function(opt) {
				var _this = this;
				this.autoConnectDeviceId = uni.getStorageSync('printerDeviceId') || '';
				uni.notifyBLECharacteristicValueChange({
					deviceId: _this.app.globalData.BLEInformation.deviceId,
					serviceId: _this.app.globalData.BLEInformation.notifyServiceId,
					characteristicId: _this.app.globalData.BLEInformation.notifyCharaterId,
					state: true,
					success: function(res) {
						// 说明已经连接上，不再执行自动连接，只初始化上次的蓝牙搜索列表
						_this.deviceList = _this.app.globalData.bluetoothDevices || [];
						_this.connectedDevice = _this.deviceList.find(val => val.deviceId == _this.autoConnectDeviceId) || {};
						opt.successCallback && opt.successCallback();
						
						uni.onBLECharacteristicValueChange(function(r) {
							console.log(
								`characteristic ${r.characteristicId} has changed, now is ${r}`
								)
							var result = _this.ab2hex(r.value)
							console.log("返回" + result)
							var tip = ''
							if (result == 0) { //正常
								tip = "正常"
							} else if (result == 4) { //缺纸
								tip = "缺纸"
							} else if (result == 5) { //开盖、缺纸
								tip = "开盖、缺纸"
							} else if (result == 41) {
								tip = "开盖"
							} else if (result == 40) { //其他错误
								tip = "其他错误"
							} else { //未处理错误
								tip = "未知错误"
							}
							uni.showModal({
								title: '打印机状态',
								content: tip,
								showCancel: false
							})
										
						})
					},
					fail: function(e) {
						_this.setUnconnectStatus();
						if (_this.autoConnectDeviceId) {
							console.log('执行蓝牙自动连接---')
							_this.startSearch();
						}
						opt.failCallback && opt.failCallback();
					},
				})
			},
			
			// ArrayBuffer转16进度字符串
			ab2hex(buffer) {
				var hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('');
			},
			
			// 点击搜索蓝牙
			clickSearch() {
				this.autoConnectDeviceId = '';
				this.startSearch();
			},

			// 搜索设备
			startSearch: function() {
				var that = this
				uni.openBluetoothAdapter({
					success: function(res) {
						uni.getBluetoothAdapterState({
							success: function(res) {
								console.warn('openBluetoothAdapter success', res)
								if (res.available) {
									if (res.discovering) {
										// 若 点击""搜索蓝牙设备"按钮之前，BLE适配器正在搜索，则放弃上次设备搜索
										uni.stopBluetoothDevicesDiscovery({
											success: function(res) {
												console.log(res)
											}
										})
									} else {
										// that.startBluetoothDevicesDiscovery()
										that.getBluetoothDevices()
									}
									that.checkPemission()
								} else {
									uni.showModal({
										title: '提示',
										content: '本机蓝牙不可用',
										showCancel: false
									})
								}
							},
						})
					},
					fail: function(res) {
						console.error(res);
						uni.showModal({
							title: '提示',
							content: '蓝牙初始化失败，请检查蓝牙',
							showCancel: false
						})
						setTimeout(() => {
							uni.showModal({
								content: JSON.stringify(res),
								showCancel: false
							})
						}, 3000)
					}
				})
			},


			// 获取蓝牙设备信息
			getBluetoothDevices: function() {
				var that = this
				console.log("start search")
				
				if (this.autoConnectDeviceId == '') {
					uni.showLoading({
						title: '正在搜索',
						mask: true,
					})
				}

				// this.isScanning = true;
				// 在success函数中，只是将搜索到的蓝牙设备，添加到 全局对象Data的deviceList字段中，并没有调用接口，在页面上显示已经搜索到的蓝牙设备
				// 因为 使用了 <scroll-view> 视图组件，该组件会自动定时渲染，渲染时会执行 wx:for ="{{deviceList}}"，异步将已经添加到deviceList中的蓝牙设备，显示在页面上
				uni.startBluetoothDevicesDiscovery({
					success: function(res) {
						console.log(res)
						// 5秒后，执行 function()，即执行 uni.getBluetoothDevices()
						setTimeout(function() {
							uni.getBluetoothDevices({
								success: function(res) {
									var devices = []
									console.log("device.len: ", res.devices.length);
									console.log(res.devices);
									for (var i = 0; i < res.devices.length; ++i) {
										if (res.devices[i].name != "未知设备") {
											devices.push(res.devices[i])
										}
									}
									that.deviceList = devices;
									that.app.globalData.bluetoothDevices = devices;
									
									// that.isScanning = false;

									uni.hideLoading()
									uni.stopPullDownRefresh()
									uni.stopBluetoothDevicesDiscovery({
										success: function(res) {
											console.log("停止搜索蓝牙")
										}
									})
									
									// 是自动连接就直接连接设备
									if (that.autoConnectDeviceId != '') {
										that.connectBluetooth(that.autoConnectDeviceId);
									}
								},
							})
						}, 5000)
					},
					fail: function(res) {
						uni.hideLoading()
						uni.showModal({
							content: JSON.stringify(res),
							showCancel: false
						})
						uni.stopBluetoothDevicesDiscovery()
					}
				})
			},
			
			// android 6.0以上需授权地理位置权限
			checkPemission: function() {
				var that = this
				var platform = this.app.globalData.BLEInformation.platform
				if (platform == "ios") {
					this.app.globalData.platform = "ios"
					that.getBluetoothDevices()
				} else if (platform == "android") {
					this.app.globalData.platform = "android"
					console.log(this.app.getSystem().substring(this.app.getSystem().length - (this.app.getSystem()
							.length - 8), app
						.getSystem().length - (this.app.getSystem().length - 8) + 1))
					if (this.app.getSystem().substring(this.app.getSystem().length - (this.app.getSystem().length - 8),
							app
							.getSystem().length - (this.app.getSystem().length - 8) + 1) > 5) {
						uni.getSetting({
							success: function(res) {
								console.log(res)
								if (!res.authSetting['scope.userLocation']) {
									uni.authorize({
										scope: 'scope.userLocation',
										complete: function(res) {
											that.getBluetoothDevices()
										}
									})
								} else {
									that.getBluetoothDevices()
								}
							}
						})
					}
				}
			},

			// 点击某个搜索到的蓝牙设备后，将触发该函数调用
			bindViewTap: function(e) {
				var deviceId = e.currentTarget.dataset.title;
				this.autoConnectDeviceId = '';
				this.connectBluetooth(deviceId);
			},
			
			// 根据deviceid连接蓝牙设备
			connectBluetooth(deviceId) {
				var _this = this;
				if (_this.app.globalData.BLEInformation.deviceId) {
					uni.showToast({
						title: '请先断开当前连接',
						icon: 'none'
					})
					return;
				}
				
				uni.stopBluetoothDevicesDiscovery({
					success: function(res) {
						console.log(res)
					},
				})
				
				// 获取蓝牙适配器状态，非连接状态且正常才可建立连接
				_this.listNum = 0;
				_this.writeCharacter = false;
				_this.readCharacter = false;
				_this.notifyCharacter = false;
				
				if (this.autoConnectDeviceId == '') {
					uni.showLoading({
						title: '正在连接',
					})
				}
				
				uni.createBLEConnection({
					deviceId: deviceId,
					success: function(res) {
						console.log(res)
						_this.app.globalData.BLEInformation.deviceId = deviceId
						_this.getSeviceId()
					},
					fail: function(e) {
						console.error(e)
						var text = '蓝牙连接失败'
						if (e.errCode == -1) {
							// {errno: 1509007, errCode: -1, errMsg: "createBLEConnection:fail:already connect"}
							text = '已经连接该设备';
						}
						uni.showToast({
							title: text,
							duration: 2500,
							icon: 'none'
						})
				
						// uni.hideLoading()
					},
					complete: function(e) {
						console.log(e)
					}
				})
			},

			// 获取蓝牙设备服务
			getSeviceId: function() {
				var that = this
				var platform = this.app.globalData.BLEInformation.platform
				var _deviceId = that.app.globalData.BLEInformation.deviceId
				uni.getBLEDeviceServices({
					deviceId: _deviceId,
					success: function(res) {
						console.warn("1111111111");
						console.log(res)
						console.warn("1.22222222");
						that.services = res.services
						that.getCharacteristics()
					},
					fail: function(e) {
						console.log(e)
						uni.showToast({
							title: e.errMsg,
							icon: 'none'
						})
					},
					complete: function(e) {
						console.log(e)
					}
				})
			},

			// 获取服务特性
			getCharacteristics: function() {
				var that = this
				var list = that.services
				var num = that.listNum
				var write = that.writeCharacter
				var read = that.readCharacter
				var notify = that.notifyCharacter
				var deviceId = that.app.globalData.BLEInformation.deviceId;
				console.warn("2.22222222222 write: " + write + ", notify: " + notify + ", read: " + read);
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: list[num].uuid,
					success: function(res) {
						console.log(res)
						for (var i = 0; i < res.characteristics.length; ++i) {
							var properties = res.characteristics[i].properties
							var item = res.characteristics[i].uuid
							if (!notify) {
								if (properties.notify) {
									that.app.globalData.BLEInformation.notifyCharaterId = item
									that.app.globalData.BLEInformation.notifyServiceId = list[num].uuid
									notify = true
								}
							}
							if (!write) {
								if (properties.write) {
									that.app.globalData.BLEInformation.writeCharaterId = item
									that.app.globalData.BLEInformation.writeServiceId = list[num].uuid
									write = true
								}
							}
							if (!read) {
								if (properties.read) {
									that.app.globalData.BLEInformation.readCharaterId = item
									that.app.globalData.BLEInformation.readServiceId = list[num].uuid
									read = true
								}
							}
						}
						if (!notify || !write) { // 发现read是始终取不到的，也不需要这个值
							// if (!write || !notify || !read) {
							num++
							that.writeCharacter = write;
							that.readCharacter = read;
							that.notifyCharacter = notify;
							that.listNum = num;

							if (num == list.length) {
								console.warn("555555555555");
								/* uni.showModal({
								  title: '提示',
								  content: '找不到该读写的特征值',
								  showCancel: false
								}) */
							} else {
								console.warn("6666666666666666");
								that.getCharacteristics()
							}
						} else {
							uni.setStorageSync('printerDeviceId', deviceId);
							that.connectedDevice = that.deviceList.find(val => val.deviceId == deviceId && val.RSSI != 0) || {}
							
							uni.showToast({
								title: '蓝牙连接成功',
								duration: 2500,
							})
							/* uni.showModal({
								title: '蓝牙连接成功',
								showCancel: false,
							}) */
							
							// 跳转回到主页
							// that.goToBack()
						}
					},
					fail: function(e) {
						console.log(e)
					},
					complete: function(e) {
						console.log("write:" + that.app.globalData.BLEInformation.writeCharaterId)
						console.log("read:" + that.app.globalData.BLEInformation.readCharaterId)
						console.log("notify:" + that.app.globalData.BLEInformation.notifyCharaterId)
					}
				})
			},

			onReachBottom() {
				if (!this.moreFlag) {
					if (this.orderList.length != 0 && this.orderList.length % this.pageSize == 0) {
						this.pageNo = this.pageNo + 1;
						this.moreFlag = true
						this.getAfterSalesList();
						setTimeout(() => {
							this.moreFlag = false;
						}, 1000)
					}
				}
			}
		}
	}
</script>

<style lang="scss">
	.bluetooth {
		/deep/ .u-drawer {
			z-index: 100 !important;
		}

		.top {
			background-color: #fff;
			text-align: center;
			padding: 18rpx 0;
			position: relative;
			font-size: 32rpx;
			font-weight: bold;
			line-height: 2;
			margin-bottom: 40rpx;

			image {
				width: 30rpx;
				height: 30rpx;
				transform: rotate(90deg);
				position: absolute;
				left: 40rpx;
				top: calc((100% - 30rpx) / 2);
			}
		}
		
		.b-btn {
			background-color: #20bdf6;
			margin: 0 auto 40rpx;
			border-radius: 2rpx;
			color: #fff;
			font-size: 14px;
			width: 128px;
			&.btn-la {
				margin-bottom: 60rpx;
			}
		}
		.device-item{
			>view {
				padding: 5px 23px;
				border-bottom: 1px solid #e8e8e8;
				position: relative;
				&.connected {
					background-color: #20bdf6;
					color: #fff;
					.c-status {
						color: #fff;
					}
				}
				.c-status {
					position: absolute;
					font-size: 12px;
					bottom: 10rpx;
					right: 18rpx;
					color: #9b9b9b;
				}
			}
		}
		
	}
</style>